package com.trace.meat.filter;

import com.trace.meat.config.ParameterServletRequestWrapper;
import com.trace.meat.entity.AdminAcct;
import com.trace.meat.entity.Ent;
import com.trace.meat.service.AdminAcctService;
import com.trace.meat.service.EntService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;



@WebFilter(urlPatterns = "/*",filterName ="RequestFilter")
public class RequestFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    EntService entService;
    @Autowired
    AdminAcctService adminAcctService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        String url = request.getRequestURI();
        Map<String, String[]> extraParams = new HashMap<String, String[]>();
        if(token==null){

        }
        String urls[] = {
                "/ent/login",
                "/ent/register",
                "/admin/login",
                "/admin/register"
        };
        for (String item : urls){
            if (item.equals(url)){
                filterChain.doFilter(servletRequest, servletResponse);
                return ;
            }
        }
        if(url.startsWith("/admin")) {
            AdminAcct adminAcct=adminAcctService.queryByToken(token);
            if(adminAcct==null){
                filterChain.doFilter(servletRequest, servletResponse);
                return ;
            }
            extraParams.put("id", new String[]{String.valueOf(adminAcct.getId())});
            System.out.println("id:"+String.valueOf(adminAcct.getId()));

        }
        else if(url.startsWith("/ent")){
            Ent ent=entService.queryByToken(token);
            if(ent==null){
                filterChain.doFilter(servletRequest, servletResponse);
                return ;
            }
            extraParams.put("eid", new String[]{String.valueOf(ent.getEid())});
            System.out.println("eid:"+String.valueOf(ent.getEid()));
        }
        //利用原始的request对象创建自己扩展的request对象并添加自定义参数
        ParameterServletRequestWrapper requestParameterWrapper = new ParameterServletRequestWrapper(request);
        requestParameterWrapper.addAllParameters(extraParams);
        filterChain.doFilter(requestParameterWrapper, servletResponse);
    }

    @Override
    public void destroy() {

    }

}
